<template>
  <basic-container class="menu-container">
    <div class="menu-header">
      <ArrowLeftBold
        @click="handleBack"
        width="24"
        height="24"
        style="padding-top: 4px; cursor: pointer"
        title="返回"
      />
      <p class="menu-title">{{ trialForm.name }}</p>
    </div>
    <div class="menu-tabs">
      <avue-crud
        :option="options"
        v-model:search="search"
        v-model:page="page"
        v-model="form"
        :table-loading="loading"
        :data="data"
        :before-open="beforeOpen"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template #menu-left>
          <el-button type="primary" :icon="Plus" plain @click="handleMenu(0)">新建变量 </el-button>
          <el-button type="primary" :icon="DocumentChecked" plain @click="handleMenu(1)"
            >导出变量
          </el-button>
<!--          <el-button
            type="primary"
            :icon="DocumentChecked"
            plain
            @click="handleMenu(2)"
            v-if="routerQuery.btnType != '3'"
            >导出数据分析
          </el-button>-->
          <!-- <el-button
            type="primary"
            plain
            @click="handleMenu(3)"
            >重 置
          </el-button> -->
        </template>
        <template #menu="{ row, index }">
          <el-button text type="primary" @click="handleMenu(4, row, index)">预 览 </el-button>
          <el-button text type="primary" @click="handleMenu(5, row, index)">编 辑 </el-button>
          <el-button text type="primary" @click="handleMenu(6, row, index)">删 除 </el-button>
        </template>
      </avue-crud>
    </div>
  </basic-container>
</template>
<script setup>
import { Plus, DocumentChecked } from '@element-plus/icons-vue';
import {
  getList,
  getDetail,
  add,
  update,
  remove,
} from '@/api/variablemanagement/variableManagement';
import { getTrialDetail } from '@/api/trial/trial';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import website from '@/config/website';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const store = useStore();
const routerQuery = ref({});
routerQuery.value = route.query;

let crud = ref(null);
const options = ref({
  height: 'auto',
  calcHeight: 30,
  tip: false,
  searchShow: true,
  searchMenuSpan: 6,
  border: true,
  index: true,
  viewBtn: true,
  selection: true,
  dialogClickModal: false,
  indexWidth: 80,
  indexLabel: '编号',
  align: 'center',
  searchMenuSpan: 18,
  searchMenuPosition: 'right',
  addBtn: false,
  viewBtn: false,
  delBtn: false,
  editBtn: false,
  column: [
    {
      label: '变量名称',
      prop: 'name',
      type: 'input',
      search: true,
      overHidden: true,
    },
    {
      // groupId
      label: '所属分组',
      prop: 'groupId',
      type: 'select',
      dicUrl: `/api/blade-group/group/groupListOfTrial?trialId=${routerQuery.value.trialId}`,
      props: {
        label: 'name',
        value: 'id',
      },
      filterable: true,
      overHidden: true,
    },
    {
      label: '数据类型',
      prop: 'dataType',
      type: 'select',
      dicUrl: '/api/blade-system/dict-biz/dictionary?code=variable_management_data_type',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      filterable: true,
      overHidden: true,
    },
    {
      label: '创建时间',
      prop: 'createTime',
      type: 'input',
    },
    {
      label: '创建人',
      prop: 'createUser',
      type: 'select',
      dicUrl: `/blade-system/user/user-list`,
      props: {
        label: 'realName',
        value: 'id',
      },
      filterable: true,
      overHidden: true,
    },
  ],
});
const form = ref({});
const query = ref({
  shareType: 1,
});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
const data = ref([]);
// ids 计算属性
const ids = computed(() => {
  return selectionList.value.map(ele => ele.id).join(',');
});
/*
  type 0:新建变量
  type 1:导出变量
  type 2:导出数据分析
  type 3:重置
  type 4:预览
  type 5:编辑
  type 6:删除
*/
const handleMenu = (type, row = {}, index = null) => {
  const actions = {
    0: () => {
      router.push({
        path: '/trial/variableAdd',
        query: {
          ...routerQuery.value,
        },
      });
    },
    1: () => {
      if (selectionList.value.length === 0) {
        ElMessage.warning('请选择至少一条数据');
        return;
      }
      console.log(ids.value);
      let downloadUrl = `/blade-variablemanagement/variableManagement/exportVariable?${
        website.tokenHeader
      }=${getToken()}`;
      let values = {
        ids: ids.value,
      };
      ElMessageBox.confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
          downloadXls(res.data, `变量导出${dateNow()}.xlsx`);
          NProgress.done();
        });
      });
    },
    4: () => {
      router.push({
        path: '/trial/variableAdd',
        query: {
          ...routerQuery.value,
          variableId: row.id,
          variableView: '1',
        },
      });
    },
    5: () => {
      router.push({
        path: '/trial/variableAdd',
        query: {
          ...routerQuery.value,
          variableId: row.id,
        },
      });
    },
    6: () => {
      crud.value.rowDel(row, index);
    },
  };

  // 执行对应的操作
  if (actions[type]) actions[type]();
};

// 返回
const handleBack = () => {
  delete routerQuery.value.btnType;
  router.replace({
    path: '/trial/menu',
    query: {
      ...routerQuery.value,
    },
  });
};
const rowSave = (row, done, loading) => {
  add(row).then(
    res => {
      onLoad(page.value);
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      done();
    },
    error => {
      loading();
      window.console.log(error);
    }
  );
};
const rowUpdate = (row, index, done, loading) => {
  update(row).then(
    () => {
      onLoad(page.value);
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      done();
    },
    error => {
      loading();
      console.log(error);
    }
  );
};
const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};
const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(ids.value);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      crud.value.toggleSelection();
    });
};
const searchReset = () => {
  query.value = {};
  onLoad(page.value, query.value);
};
const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  onLoad(page.value, params);
  done();
};
const beforeOpen = (done, type) => {
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = res.data.data;
    });
  }
  done();
};
const selectionChange = list => {
  selectionList.value = list;
};
const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};
const currentChange = currentPage => {
  page.value.currentPage = currentPage;
};
const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
};
const refreshChange = () => {
  onLoad(page.value, query.value);
};
const onLoad = (page, params = {}) => {
  loading.value = true;

  const { name, lbType } = query.value;

  let values = {
    name_: name,
    lbType_: lbType,
    descs: 'create_time',
    type: routerQuery.value.btnType,
    trial: routerQuery.value.trialId,
    ...params,
  };

  getList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    data.value = DATA.records;
    loading.value = false;
    selectionClear();
  });
};

const trialForm = ref({});
const initTrialDetail = async id => {
  let res = await getTrialDetail(id);
  trialForm.value = res.data.data;
};
onMounted(() => {
  if (routerQuery.value.trialId) {
    initTrialDetail(routerQuery.value.trialId);
  }
});
</script>
<style lang="scss" scoped>
.menu-container {
  ::v-deep .basic-container__card {
    height: 100%;
  }
  ::v-deep .el-card__body {
    height: 100%;
  }
  height: 100%;
  overflow-y: hidden;
}
.menu-header {
  width: 100%;
  height: auto;
  margin-bottom: 10px;
  padding-bottom: 20px;
  display: flex;
  align-items: center;
  border-bottom: 2px solid #ebeef5;
}
.menu-title {
  font-size: 28px;
  margin-top: 0;
  // margin-left: 10px;
  margin-bottom: 0;
}
.menu-content {
  width: 95%;
  height: calc(100% - 120px);
  display: flex;
  justify-content: center;
  overflow-y: auto;
}
</style>
